define(['moment'], function () {
    return ['$scope', '$rootScope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', '$datePicker',
        function ($scope, $rootScope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $datePicker) {

            $scope.init = function () {
                $scope.printData = {
                    item_no: '', 
                    item_name: '',
                    wo_no: '', 
                    barcode_no: '',
                    Copies: '1'
                };
                $scope.printDataList = [];
                $scope.selectedList = [];
                $scope.isShowPrintBtn = []; // isShowPrintBtn 用來判斷是否要打開補印按鈕
                $scope.printList = []; // 列印詳情
            };

            $scope.back = function () {
                $scope.$root.hideMenu();
                $scope.$root.changeProgram('home', true);
            };

            // 取得產品編號
            $scope.loadItemNo = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 'opm_product_no_info_get',
                    pageRecord: 50,
                    condition: [
                        {name:$filter('translate')('common.queryList.item_c'), column_name:'ProductNo', query_mode:'2', value: $scope.printData.item_no}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.item_c'), code:'product_no'},
                        {label:$filter('translate')('common.queryList.item_n'), code:'product_name'}
                    ],
                    setCondition:function(conditions){
                        conditions.push(
                            {column_name:'IssueState', query_mode:'0', value:'2', merge_condition_model:'AND' },
                            {column_name:'CurVersion', query_mode:'0', value:'1', merge_condition_model:'AND' },
                        );
                        return conditions;
                    },
                    selectCode: $scope.printData.item_no || '',
                    confirm : function(selectItem){
                        $scope.printData.item_no = selectItem.product_no;
                        $scope.printData.item_name = selectItem.product_name;
                    }
                });
            };

            // 输入打印份数
            $scope.input_print_qty = function (event, Copies) {
                var target = event.currentTarget;
                angular.element(target).addClass('is-focus');
                $calculater.open(function (num, dialogNum) {
                    if (num == 0) {
                        $rootScope.showAlert($filter('translate')('B1201.msg.column02'));
                        return;
                    }
                    angular.element(target).removeClass('is-focus');
                    $scope.printData.Copies = num;
                    dialogNum.hide();
                },
                function (dialogNum) {
                    angular.element(target).removeClass('is-focus');
                    dialogNum.hide();
                },
                {
                    defaultNum: $scope.printData.Copies,
                    decimal: false
                });
            };

            // 取得工單編號
            $scope.loadWoNo = function () {
                $MMWService.showQueryListPNIG({
                    page_mode: 'opm_wo_no_info_get',
                    pageRecord: 50,
                    condition: [
                        {name:$filter('translate')('common.queryList.wo_c'), column_name:'A.MONo', query_mode:'2', value:$scope.printData.wo_no}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.wo_c'), code:'wo_no'}
                    ],
                    setCondition:function(conditions){
                        if($scope.printData.item_no){
                            conditions.push(
                                {column_name:'A.PRODUCTNO', query_mode:'2', value: $scope.printData.item_no, merge_condition_model:'AND'}
                            );
                        }
                        return conditions;
                    },
                    selectCode: $scope.printData.wo_no || '',
                    confirm : function(selectItem){
                        $scope.printData.wo_no = selectItem.wo_no;
                    }
                });
            };

            // 查詢標籤補印資料
            $scope.search = function () {
                var query_condition_info = [];
                if($scope.printData.item_no){
                    query_condition_info.push({column_name: "a.PRODUCTNO", query_mode: "2", value: $scope.printData.item_no, merge_condition_model: "AND"});
                }
                if($scope.printData.wo_no){
                    query_condition_info.push({column_name: "a.mono", query_mode: "2", value: $scope.printData.wo_no, merge_condition_model: "AND"});
                }
                if($scope.printData.barcode_no){
                    query_condition_info.push({column_name: "a.BarCode", query_mode: "2", value: $scope.printData.barcode_no, merge_condition_model: "AND"});
                }

                //  20230103 modify by shiwl for#  0154529: 力邦合信，正式区。标签补印问题 
                if(query_condition_info.length == 0) {
                    $scope.$root.showAlert($filter('translate')('B1201.msg.column08'));
                    return false;
                }  

                $MMWService.pageNumberInfoGet({
                    page_mode: 'reprint_data_info_get',
                    query_condition_info: query_condition_info
                }, function(itemList){
                    if(itemList && itemList.length > 0){
                        $scope.printDataList = itemList;
                        $scope.printDataList.forEach(function(item){
                            item.isSelect = false;
                        });
                    } else {
                        $scope.printDataList = [];
                        $scope.selectedList = [];
                        $scope.isShowPrintBtn = [];
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });
            };

            // 勾選按鈕
            $scope.itemClick = function(item){
                if(!item.isSelect)
                {
                    item.isSelect = true;
                    // isShowPrintBtn 用來判斷是否要打開補印按鈕
                    $scope.isShowPrintBtn.push(item);
                }
                else
                {
                    item.isSelect = false;
                    // isShowPrintBtn 用來判斷是否要打開補印按鈕
                    if($scope.isShowPrintBtn.indexOf(item) != -1)
                        $scope.isShowPrintBtn.splice($scope.isShowPrintBtn.indexOf(item), 1);
                };
            };

            // 載入條碼標籤明細
            $scope.loadBarcodeDetail = function(item){
                $MMWService.pageNumberInfoGet({
                    page_mode: 'reprint_data_detail_info_get',
                    query_condition_info: [
                        {column_name: "a.BarCode", query_mode: "0", value: item.barcode_no, merge_condition_model: "AND"}
                    ]
                }, function(itemList){
                    if(itemList && itemList.length > 0){
                        $scope.selectedList = itemList;
                    } else {
                        $scope.selectedList = [];
                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                    };
                });
            };

            // 送出補印
            var pdf_url;
            $scope.print = function () {
                var reprint_data = [];
                $scope.printDataList.forEach(function(item){
                    if(item.isSelect)
                        reprint_data.push(item);
                });
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.reprint_data_process',
                    content : {
                        reprint_data: reprint_data,
                        Copies: $scope.printData.Copies
                    },
                    success : function(data){
                        if(data.runcard_pdf_get.length == 0 && data.command_lines.length == 0)
                        {
                            $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                        } 
                        else
                        {
                            for(var i = 0; i < reprint_data.length; i++){
                                $scope.printList.push({
                                    printNo: reprint_data[i].barcode_no,
                                    printType: '3' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                                });
                            }

                            // 執行標籤列印
                            if(data.command_lines && data.command_lines.length > 0)
                            {
                                printTag(data.command_lines, 0, data.runcard_pdf_get);
                            } 
                            // 執行 PDF列印
                            if(data.runcard_pdf_get && data.runcard_pdf_get.length > 0)
                            {
                                // 20201121 modify by 外包 for M#80272: 增加不同的标签可以多条打印的功能
                                let tempRuncardPdf = [];
                                data.runcard_pdf_get.forEach(r => {
                                    if (r.printCount > 1){
                                        for(var i = 0; i < r.printCount; i++){
                                            tempRuncardPdf.push({
                                                url_pdf: r.url_pdf,
                                                width: r.width,
                                                height: r.height,
                                                printCount: 1
                                            });
                                        }
                                    }else {
                                        tempRuncardPdf.push(r);
                                    }
                                });
                                printBatch(tempRuncardPdf, 0);
                            }
                            $scope.printDataList = [];
                            $scope.selectedList = [];
                            $scope.isShowPrintBtn = [];
                        }
                    }
                });
            };

            // 條碼列印
            var isError = false;
            function printTag(commandLines, index, runcard_pdf_get){
                if(commandLines && index < commandLines.length){
                    if(window.nodeRequire){
                        var exec = window.nodeRequire('child_process').exec;
                        exec(commandLines[index], function(error, stdout, stderr){
                            if (error) {
                                isError = true;
                                console.log(error);
                                $rootScope.showAlert($filter('translate')('B1202.msg.cantprint'));
                            }
                            index = index +1;
                            printTag(commandLines, index, runcard_pdf_get);
                        });
                    }
                } else {
                    if(!isError){
                        isError = false;
                        $scope.$root.showToast($filter('translate')('common.msg.success'));
                        if(runcard_pdf_get && runcard_pdf_get.length === 0){
                            printWiplogProcess();
                        } 
                    }
                }
            };

            // 批量打印
            function printBatch(runcard_pdf_get, index){
                if (index < runcard_pdf_get.length){
                    pdf_url = runcard_pdf_get[index].url_pdf;
                    if(pdf_url.indexOf('http://') == -1){
                        pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                    }
                    var width = runcard_pdf_get[index].width;
                    var height = runcard_pdf_get[index].height;
                    print(pdf_url, width, height, function callback(){
                        index = index + 1;
                        printBatch(runcard_pdf_get, index);
                    });
                    
                }
            };

             // PDF列印
            function print(pdf_url, width, height, callback){
                if(window.nodeRequire){
                    var sumatraPDF = window.nodeRequire('sumatra-pdf');
                    if(sumatraPDF){
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try{
                            // 20240321 modify by Alan for#159805 : electron升級後，兼容新舊版本
                            const remote = window.nodeRequire('electron').remote || window.nodeRequire('@electron/remote');
                            RuncardPath = remote.app.getAppPath();
                        }catch(e){
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if(!fs.existsSync(RuncardPath)){
                            fs.mkdirSync(RuncardPath);
                        }

                        // 20240222 add by Alan for#158151 : 清除Runcard目錄下未開啟的舊檔案
                        // 20240408 modify by Alan for#139948 : 改成同步讀取，避免刪除檔案後立即列印造成找不到檔案
                        fs.readdirSync(RuncardPath, (err, files) => {
                            if (err) {
                                console.log(err);
                            }
                            //listing all files using forEach
                            files.forEach((file) => {
                                // Do whatever you want to do with the file
                                fs.unlink(RuncardPath + '/' + file, (err) => {
                                    if (err) {
                                        console.debug(err);
                                    }
                                })
                            });
                        })
    
                        // 20240222 add by Alan for#158151 : 增加時間戳記，避免檔名重複造成檔案開啟時無法寫入
                        let pdfPath = `${RuncardPath}/RuncardPreview_${Date.now()}.pdf`;
                        $scope.$root.downloadFile(pdf_url, pdfPath, function (dist_path) {
                            $rootScope.showLoading();
                            // 20201110 modify by WeiTing for M#80602 - 不跳列印介面，直接使用預設列印機進行列印(printToDefault)。
                            var _fn = sumatraPDF.printToDefault;
                            _fn({
                                path: dist_path,
                                settings: width > height ? 'landscape' : '',
                                success:function(){
                                    callback();
                                    printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                },
                                error:function(error){
                                    // 20201104 modify by WeiTing for M#77013 - 不清楚為何列印後，實際列印一張紙和輸入成 PDF檔案都會執行 error 區域，所以目前也先列印完成後，把列印詳情回送給後台做記錄。
                                    printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                    //console.error(error);
                                }
                            });
                        });
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            };

            // 列印完成後，需把列印詳情回送給後台做記錄
            function printWiplogProcess(){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.print_wiplog_process',
                    content : {
                        printList: $scope.printList
                    },
                    success : function(){
                        $scope.printList = [];
                    }
                });
            }
            
            // 列印詳情開窗查詢
            $scope.printInfoDialog = function(item){
                $mdDialog.dialog('module/moduleB/program/publicDialog/printInfoDialog.tmp.html',
                    function(dialog){
                        return {
                            printList: {
                                program: 'B1202',
                                repair_order_no: item.barcode_no,  // 維修單單號
                                print_user: '', // 列印人員
                                start_date: moment().subtract(3, 'days').format('YYYY-MM-DD'), // 開始日期
                                start_time: moment().subtract(3, 'days').format('HH:mm:ss'), // 開始時間
                                end_date: moment().endOf('day').format('YYYY-MM-DD'), // 結束日期
                                end_time: moment().endOf('day').format('HH:mm:ss'), // 結束時間
                                printDetailList: []
                            },
                            init: function(){ // 初始化
                                var start_dateTime = dialog.printList.start_date + ' ' + dialog.printList.start_time, // 開始日期 + 開始時間
                                    end_dateTime = dialog.printList.end_date + ' ' + dialog.printList.end_time; // 結束日期 + 結束時間

                                $MMWService.pageNumberInfoGet({
                                    page_mode : 'print_wiplot_info_get',
                                    query_condition_info : [
                                        {column_name: 'PRINTNO', query_mode:'2', value: '%' + dialog.printList.repair_order_no + '%', merge_condition_model:'AND'}, // 維修單單號
                                        {column_name: 'CREATOR', query_mode:'2', value: '%' + dialog.printList.print_user + '%', merge_condition_model:'AND'}, // 列印人員
                                        {column_name: 'CREATEDATE', query_mode:'4', value: start_dateTime, merge_condition_model:'AND'}, // 列印时间 - 開始
                                        {column_name: 'CREATEDATE', query_mode:'5', value: end_dateTime, merge_condition_model:'AND'}, // 列印时间 - 結束
                                        {column_name: 'PRINTTYPE', query_mode:'0', value: '3', merge_condition_model:'AND'} // 列印類型 - 1:批次流程卡; 2:系统出站标签; 3:末站标签打印; 4:外包单打印; 5:模具维修单打印;
                                    ]
                                }, function (response) {
                                    if(response && response.length > 0){
                                        dialog.printList.printDetailList = response;
                                    } else {
                                        dialog.printList.printDetailList = [];
                                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                    }
                                });
                            },
                            back: function() {
                                dialog.hide();
                            },
                            search: function() { // 查詢
                                var start_dateTime = dialog.printList.start_date + ' ' + dialog.printList.start_time, // 開始日期 + 開始時間
                                    end_dateTime = dialog.printList.end_date + ' ' + dialog.printList.end_time; // 結束日期 + 結束時間

                                $MMWService.pageNumberInfoGet({
                                    page_mode : 'print_wiplot_info_get',
                                    query_condition_info : [
                                        {column_name: 'PRINTNO', query_mode:'2', value: '%' + dialog.printList.repair_order_no + '%', merge_condition_model:'AND'}, // 維修單單號
                                        {column_name: 'CREATOR', query_mode:'2', value: '%' + dialog.printList.print_user + '%', merge_condition_model:'AND'}, // 列印人員
                                        {column_name: 'CREATEDATE', query_mode:'4', value: start_dateTime, merge_condition_model:'AND'}, // 列印时间 - 開始
                                        {column_name: 'CREATEDATE', query_mode:'5', value: end_dateTime, merge_condition_model:'AND'}, // 列印时间 - 結束
                                        {column_name: 'PRINTTYPE', query_mode:'0', value: '3', merge_condition_model:'AND'} // 列印類型 - 1:批次流程卡; 2:系统出站标签; 3:末站标签打印; 4:外包单打印; 5:模具维修单打印;
                                    ]
                                }, function (response) {
                                    if(response && response.length > 0){
                                        dialog.printList.printDetailList = response;
                                    } else {
                                        dialog.printList.printDetailList = [];
                                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                    }
                                });
                            },
                            changeStartDate: function() { // 更改開始日期
                                $datePicker.open(dialog.printList.start_date,
                                    function(dialogType){
                                        if(moment(dialogType.datePacker.pickDate).isBefore(dialog.printList.end_date)
                                        || moment(dialogType.datePacker.pickDate).isSame(dialog.printList.end_date))
                                        {
                                            dialog.printList.start_date = moment(dialogType.datePacker.pickDate).format('YYYY-MM-DD');
                                            dialogType.hide();
                                        }  
                                        else 
                                            $scope.$root.showAlert($filter('translate')('printInfoDialog.showAlert.column01')); // 開始日期不能大於結束日期！
                                    },
                                    function(dialogType){
                                        dialogType.hide();
                                    },{}
                                );
                            },
                            changeEndDate: function() { // 更改結束日期
                                $datePicker.open(dialog.printList.end_date,
                                    function(dialogType){
                                        if(moment(dialogType.datePacker.pickDate).isAfter(dialog.printList.start_date)
                                        || moment(dialogType.datePacker.pickDate).isSame(dialog.printList.start_date))
                                        {
                                            dialog.printList.end_date = moment(dialogType.datePacker.pickDate).format('YYYY-MM-DD');
                                            dialogType.hide();
                                        }  
                                        else
                                            $scope.$root.showAlert($filter('translate')('printInfoDialog.showAlert.column02')); // 結束日期不能小於開始日期！
                                    },
                                    function(dialogType){
                                        dialogType.hide();
                                    },{}
                                );
                            }
                        }
                    }
                );
            };

        }
    ];
});
